package main

import (
	"fmt"
	"os"
	"time"
	rss "github.com/jteeuwen/go-pkg-rss"
	restdb "cloud9lib.googlecode.com/hg/restdb/http"
	"flag"
)

func main() {
	flag.Parse()
	
	PollFeed(flag.Arg(0), 5)
}

func PollFeed(uri string, timeout int) {
	feed := rss.New(timeout, true, chanHandler, itemHandler)

	for {
		if err := feed.Fetch(uri); err != nil {
			fmt.Fprintf(os.Stderr, "[e] %s: %s\n", uri, err)
			return
		}

		<-time.After(feed.SecondsTillUpdate() * 1e9)
	}
}

func chanHandler(feed *rss.Feed, newchannels []*rss.Channel) {
	fmt.Printf("%d new channel(s) in %s\n", len(newchannels), feed.Url)

	for _, ch := range newchannels {
		fmt.Println(ch.Title, ch.Description)
		fmt.Println(ch)
	}
}

func itemHandler(feed *rss.Feed, ch *rss.Channel, newitems []*rss.Item) {
	fmt.Printf("%d new item(s) in %s\n", len(newitems), feed.Url)

	for _, item := range newitems {
		fmt.Println(item.Title, item.Description)
		fmt.Println(item)

		restdb.Publish("ads", item)

		<-time.After(5 * 1e9)
	}
}
